package com.cyy.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cyy.base.exception.LearningException;
import com.cyy.base.model.PageParams;
import com.cyy.base.model.PageResult;
import com.cyy.content.mapper.CourseBaseMapper;
import com.cyy.content.mapper.CourseCategoryMapper;
import com.cyy.content.mapper.CourseMarketMapper;
import com.cyy.content.model.dto.AddCourseDto;
import com.cyy.content.model.dto.CourseBaseInfoDto;
import com.cyy.content.model.dto.EditCourseDto;
import com.cyy.content.model.dto.QueryCourseParamsDto;
import com.cyy.content.model.po.CourseBase;
import com.cyy.content.model.po.CourseCategory;
import com.cyy.content.model.po.CourseMarket;
import com.cyy.content.service.CourseBaseService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 课程基本信息 服务实现类
 * </p>
 *
 * @author cyy
 */
@Slf4j
@Service
public class CourseBaseServiceImpl extends ServiceImpl<CourseBaseMapper, CourseBase> implements CourseBaseService {

    @Autowired
    private CourseBaseMapper courseBaseMapper;

    @Autowired
    private CourseMarketMapper courseMarketMapper;

    @Autowired
    private CourseCategoryMapper courseCategoryMapper;


    @Override
    public PageResult<CourseBase> queryCourseBaseList(PageParams pageParams, QueryCourseParamsDto queryCourseParamsDto) {
        //构建查询条件对象
        LambdaQueryWrapper<CourseBase> queryWrapper = new LambdaQueryWrapper<>();
        //构建查询条件，根据课程名称查询
        queryWrapper.like(StringUtils.isNotEmpty(queryCourseParamsDto.getCourseName()), CourseBase::getName, queryCourseParamsDto.getCourseName());
        //构建查询条件，根据课程审核状态查询
        queryWrapper.eq(StringUtils.isNotEmpty(queryCourseParamsDto.getAuditStatus()), CourseBase::getAuditStatus, queryCourseParamsDto.getAuditStatus());
        //构建查询条件，根据课程发布状态查询
        queryWrapper.eq(StringUtils.isNotEmpty(queryCourseParamsDto.getPublishStatus()), CourseBase::getStatus, queryCourseParamsDto.getPublishStatus());

        //分页对象
        Page<CourseBase> page = new Page<>(pageParams.getPageNo(), pageParams.getPageSize());
        // 查询数据内容获得结果
        Page<CourseBase> pageResult = courseBaseMapper.selectPage(page, queryWrapper);
        // 获取数据列表
        List<CourseBase> list = pageResult.getRecords();
        // 获取数据总数
        long total = pageResult.getTotal();
        // 构建结果集
        PageResult<CourseBase> courseBasePageResult = new PageResult<>(list, total, pageParams.getPageNo(), pageParams.getPageSize());
        return courseBasePageResult;

    }

    /*
    新增课程表单中包括了课程基本信息、课程营销信息，需要分别向课程基本信息表、课程营销表保证数据。
     */
    @Transactional
    @Override
    public CourseBaseInfoDto addCourseBaseInfo(Long companyId, AddCourseDto courseDto) {
        //合法性校验
        if (StringUtils.isBlank(courseDto.getName())) {
//            throw new RuntimeException("课程名称为空");
            throw new LearningException("课程名称为空");
        }
        if (StringUtils.isBlank(courseDto.getMt())) {
//            throw new RuntimeException("课程分类为空");
            throw new LearningException("课程分类为空");
        }
        if (StringUtils.isBlank(courseDto.getSt())) {
//            throw new RuntimeException("课程分类为空");
            throw new LearningException("课程分类为空");
        }
        if (StringUtils.isBlank(courseDto.getGrade())) {
//            throw new RuntimeException("课程等级为空");
            throw new LearningException("课程等级为空");
        }
        if (StringUtils.isBlank(courseDto.getTeachmode())) {
//            throw new RuntimeException("教育模式为空");
            throw new LearningException("教育模式为空");
        }
        if (StringUtils.isBlank(courseDto.getUsers())) {
//            throw new RuntimeException("适应人群为空");
            throw new LearningException("适应人群为空");
        }
        if (StringUtils.isBlank(courseDto.getCharge())) {
//            throw new RuntimeException("收费规则为空");
            throw new LearningException("收费规则为空");
        }
        //新增对象
        CourseBase courseBase = new CourseBase();
        //插入课程基本信息表
        BeanUtils.copyProperties(courseDto, courseBase);
        //设置审核状态
        courseBase.setAuditStatus("202002");
        //设置发布状态
        courseBase.setStatus("203001");
        //机构id
        courseBase.setCompanyId(companyId);
        //添加时间
        courseBase.setCreateDate(LocalDateTime.now());
        //插入课程基本信息表
        int insert = courseBaseMapper.insert(courseBase);
        if (insert <= 0) {
//            throw new RuntimeException("新增课程基本信息失败");
            throw new LearningException("新增课程基本信息失败");
        }
        // 向课程营销表保存课程营销信息
        CourseMarket courseMarket = new CourseMarket();
        BeanUtils.copyProperties(courseDto, courseMarket);
        Long courseId = courseBase.getId();
        courseMarket.setId(courseId);
        int i = saveCourseMarket(courseMarket);
        if(i <= 0){
//            throw new RuntimeException("保存营销信息失败");
            throw new LearningException("保存营销信息失败");
        }

        // 查询课程基本信息及营销信息并返回
        return getCourseBaseInfo(courseId);
    }

    /**
     * 根据课程id查询课程基本信息，包括基本信息和营销信息
     * @param courseId
     * @return
     */
    public CourseBaseInfoDto getCourseBaseInfo(Long courseId) {
        //课程信息
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        if(courseBase == null){
            return null;
        }
        CourseBaseInfoDto courseBaseInfoDto = new CourseBaseInfoDto();
        BeanUtils.copyProperties(courseBase, courseBaseInfoDto);
        //课程营销信息
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);
        if(courseMarket != null){
            BeanUtils.copyProperties(courseMarket, courseBaseInfoDto);
        }
        //查询分类名称
        CourseCategory courseCategoryBySt = courseCategoryMapper.selectById(courseBase.getSt());
        courseBaseInfoDto.setStName(courseCategoryBySt.getName());
        CourseCategory courseCategoryByMt = courseCategoryMapper.selectById(courseBase.getMt());
        courseBaseInfoDto.setMtName(courseCategoryByMt.getName());
        return courseBaseInfoDto;
    }

    /**
     * 编辑课程信息
     * @param companyId
     * @param editCourseDto
     * @return
     */

    @Transactional
    @Override
    public CourseBaseInfoDto editCourseBaseInfo(Long companyId, EditCourseDto editCourseDto) {
        Long courseId = editCourseDto.getId();
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        if(courseBase == null){
            LearningException.cast("课程不存在");
        }
        //校验本机构只能修改本机构的课程
        if(!courseBase.getCompanyId().equals(companyId)){
            LearningException.cast("无法修改其它机构的课程");
        }
        //更新课程信息
        BeanUtils.copyProperties(editCourseDto, courseBase);
        courseBase.setChangeDate(LocalDateTime.now());
        int i = courseBaseMapper.updateById(courseBase);
        if(i <= 0){
            LearningException.cast("课程信息更新错误");
        }
        //封装营销信息的数据
        CourseMarket courseMarket = new CourseMarket();
        BeanUtils.copyProperties(editCourseDto, courseMarket);
        saveCourseMarket(courseMarket);
        //查询课程信息
        CourseBaseInfoDto courseBaseInfo = getCourseBaseInfo(courseId);
        return courseBaseInfo;
    }

    /**
     * 保存课程营销信息
     * @param courseMarket
     * @return
     */
    private int saveCourseMarket(CourseMarket courseMarket) {
        //收费规则
        String charge = courseMarket.getCharge();
        if(StringUtils.isBlank(charge)){
//            throw new RuntimeException("收费规则没有选择");
            throw new LearningException("收费规则没有选择");
        }
        if(charge.equals("201001")){
            if(courseMarket.getPrice() == null || courseMarket.getPrice().floatValue() <= 0){
//                throw new RuntimeException("课程收费价格不能为空且必须大于0");
                throw new LearningException("课程收费价格不能为空且必须大于0");
            }
        }
        //根据id从课程营销表查询
        CourseMarket cMarket = courseMarketMapper.selectById(courseMarket.getId());
        if(cMarket == null){
            return courseMarketMapper.insert(courseMarket);
        }else{
            BeanUtils.copyProperties(courseMarket, cMarket);
            cMarket.setId(courseMarket.getId());
            return courseMarketMapper.updateById(cMarket);
        }
    }

}
